const { URL } = require('url');

const allowedProtocols = new Set(['http:', 'https:']);

// Common safe filename: letters, numbers, space, dash, underscore, dot
const fileNameRegex = /^[A-Za-z0-9 _.-]{1,255}$/;

// Optional: allowlist of extensions; keep minimal defaults, can be extended
const defaultAllowedExtensions = new Set([
    '.txt',
    '.pdf',
    '.zip',
    '.jpg',
    '.jpeg',
    '.png',
    '.gif',
    '.csv',
    '.json',
    '.mp4',
]);

function isValidHttpUrl(value) {
    try {
        const parsed = new URL(value);
        return allowedProtocols.has(parsed.protocol);
    } catch (e) {
        return false;
    }
}

function getExtensionLower(fileName) {
    const lastDot = fileName.lastIndexOf('.');
    if (lastDot === -1) return '';
    return fileName.substring(lastDot).toLowerCase();
}

function isValidFileName(fileName) {
    return fileNameRegex.test(fileName);
}

function isAllowedExtension(fileName, allowed = defaultAllowedExtensions) {
    const ext = getExtensionLower(fileName);
    if (!ext) return false;
    return allowed.has(ext);
}

function validateDownloadInput(input, options = {}) {
    const errors = [];
    const { allowedExtensions = defaultAllowedExtensions } = options;

    if (!input || typeof input !== 'object') {
        errors.push('invalid_payload');
        return { ok: false, errors };
    }

    const { fileUrl, fileName } = input;

    if (!fileUrl || typeof fileUrl !== 'string' || !isValidHttpUrl(fileUrl)) {
        errors.push('invalid_file_url');
    }

    if (!fileName || typeof fileName !== 'string' || !isValidFileName(fileName)) {
        errors.push('invalid_file_name');
    } else if (!isAllowedExtension(fileName, allowedExtensions)) {
        errors.push('disallowed_extension');
    }

    return { ok: errors.length === 0, errors };
}

module.exports = {
    isValidHttpUrl,
    isValidFileName,
    isAllowedExtension,
    validateDownloadInput,
    defaultAllowedExtensions,
};


